import { Component, OnInit } from '@angular/core';
import {OrderService} from '../../orders/shared/order.service';
import {PromotionService} from '../shared/promotion.service';
import {MatSnackBar} from '@angular/material';
import {HeaderService} from '../../shared/header.service';
import {ActivatedRoute} from '@angular/router';

@Component({
  selector: 'app-coupons0624',
  templateUrl: './coupons0624.component.html',
  styleUrls: ['./coupons0624.component.css'],
  providers: [PromotionService]
})
export class Coupons0624Component implements OnInit {

  public phoneNumber: string;
  public couponId: string;
  public couponTitle: string;
  public couponContent: string;

  constructor(private promotionService: PromotionService,
              private headerService: HeaderService,
              private activatedRoute: ActivatedRoute,
              private snackBar: MatSnackBar) { }

  ngOnInit() {
    console.log('coupons init..');
    this.couponId = this.activatedRoute.snapshot.paramMap.get('id');
    const headerFlagSubj = this.headerService.getHeaderFlag();
    headerFlagSubj.next(false);
    this.getCoupon(this.couponId);
  }
  getCoupon(couponId: string) {
    this.promotionService.get0624Coupons(couponId).subscribe((result) => {
      this.couponTitle = result.name;
      this.couponContent = result.description;
    });
  }
  onApplyCouponsClicked(target) {
    this.promotionService.apply0624Coupons(this.couponId, this.phoneNumber).subscribe( (result) => {
      if (result === 'true') {
        this.openSnackBar('成功获取优惠券', '');
      } else {
        this.openSnackBar('您尚未注册或已经获取过此优惠券！', '');
      }
    },
      () => {
      this.openSnackBar('获取优惠券失败', '');
      });
  }

  openSnackBar(message: string, action: string) {
    this.snackBar.open(message, action, {
      duration: 2000
    });
  }
}
